import React, {Fragment, useEffect, useRef, useState,useLayoutEffect} from 'react'
import {CTable} from './Ctable'
import Typed from 'typed.js';
import ZanOrCai from "@/pages/NewTalk/zanOrCai";
const errMsg={
  "A00001":"日期校验失败",
  "A00002":"未包含查询维度",
  "A00003":"账期校验失败",
  "A00004":"省份校验失败",
  "A00005":"获取数据失败",
  "A00006":"sql生成失败",
  "A00007":"不能包含多个计算指标",
  "A00008":"数据查询为空",
  "A00009":"获取虚拟宽表数据失败",
  "A00010":"已存在指标日志未具备",
  "A00011":"已存在明细表日志未具备",
  "A00012":"维度已验证无法删除",
  "A00013":"计算表达式错误",
  "A00014":"拍照指标表达式有误",
  "A00015":"计算指标表达式有误",
  "A88888":"下游返回错误的返回",
  "A99997":"请求格式错误",
  "A99998":"请求格式错误",
  "C10000":"请求格式错误",
  "C10001":"请求服务标识错误",
  "C10002":"请求能力标识错误",
  "N20000":"能力调用超时"
}
function getData(props){
  const reaL=typeof props.content==='string'?JSON.parse(props.content):props.content
  const arr = reaL?.kpi_desc?.replace(/\\\\n|\\|\r\n/g, '\n').split("\n");
  let newArr = [];
  newArr.push(arr[0]);
  newArr.push(arr[1]);
  if(arr.length>3){
    newArr.push("");
  }else {
    newArr.push(arr[2]);
  }
  return newArr;
}
    export const RobotRes=(props)=>{
        const reaL=typeof props.content==='string'?JSON.parse(props.content):props.content
        const [talkList, setTalkList] = useState([]);
        const exportDown= async ()=>{
            const {dispatch}=props
            dispatch({
                type: 'intellectAssistant/fetchTableDownload',
                payload: {
                  name:reaL.kpi_name,
                  resp_code:reaL.resp_code,
                  final_kpi_sql:reaL?.final_kpi_sql||"",
                  kpi_sql :reaL?.kpi_sql ||"",
                  vtable_sql  :reaL?.vtable_sql  ||"",
                  ai_sql:reaL?.ai_sql  ||"",
                },
            });
        }
        const [typingCompleted1, setTypingCompleted1] = useState(false);
        const [typingCompleted2, setTypingCompleted2] = useState(false);
        const [typingCompleted3, setTypingCompleted3] = useState(false);
        const [stop, setStop] = useState(false);
        const { item,dispatch,handleScroll } = props;
        //创建实例
        const typed = useRef(null);
        //开始构造
      function createTyped(elementSelectorPrefix, talkList, onFinish) {
        //构造函数方法
        const typeText = async (elementSelector, text, onCompleteCallback) => {
          return new Promise(resolve => {
            typed.current = new Typed(elementSelector, {
              strings: [text],
              typeSpeed: 30,
              loop: false,
              showCursor: false,
              onComplete: () => {
                onCompleteCallback();
                resolve();
              },
            });
          });
        };

        //要打印哪些文字
        const runTypedSequence = async () => {
          for (let i = 0; i < talkList.length; i++) {
            const elementSelector = `.${elementSelectorPrefix}${i + 1}${props.index}`;
            //重绘时清
              const element = document.querySelector(elementSelector);

            if (element) {
              element.textContent = ''; // 清空元素内容
            }
            //执行插件
            await typeText(elementSelector, talkList[i], () => {
              if (i === 0) setTypingCompleted1(true);
              else if (i === 1) setTypingCompleted2(true);
              else if (i === 2) {
                setTypingCompleted3(true);
                setStop(true);
              }
            });
          }
           //全部打印完毕的的回调
          if (onFinish) onFinish();
        };
        runTypedSequence();
      }
      useEffect( ()=>{
          let data = getData(props);
          setTalkList(data)
        createTyped('typed', data);
          return ()=>{
            if (typed.current) { // 在这里销毁 Typed 实例
              typed.current.destroy();
            }
          }
        }
        ,[reaL])
      function changeStatus(status){
          setStop(status)
        if(status){
          typed.current.stop()
        }else {
          setTypingCompleted1(false);
          setTypingCompleted2(false);
          setTypingCompleted3(false);
          if(typed){
            typed.current.destroy();
          }
          createTyped('typed', talkList);
        }
      }
      useLayoutEffect(()=>{
        //暂时注释掉功能也好使
        // handleScroll();
      },[typingCompleted1,typingCompleted2,typingCompleted3,stop])

        return <Fragment>
          <div>
            {reaL?.resp_code?.startsWith('0') ?
             <div>
                <p className={'typed1' + props.index}/>
                <div style={{display: "flex"}}>
                  {typingCompleted1 && (<p className={'typed2' + props.index}/>)}
                  {typingCompleted2 && (
                    <p onClick={exportDown} style={{color: "#1067ee", textDecoration: "underline", cursor: "pointer"}}
                       className={'typed3' + props.index}/>)}
                </div>
                {typingCompleted3 && reaL.input_column && (<CTable table={reaL.input} columns={reaL.input_column}/>)}
              </div> : (errMsg[reaL.resp_code] ? errMsg[reaL.resp_code] : '未知错误！')}
          </div>
          {reaL?.resp_code?.startsWith('0') ?
            <ZanOrCai index={item.index} islike={item.islike} resp={item.resp} question={item.question}
                      predictStatus={item.predictStatus} createTime={item.createTime}
                      changeStatus={changeStatus}
                      stop={stop}
                      dispatch={dispatch}/> : ""}
        </Fragment>
    }
